package com.yimi.yinhepda.views.stockCheck_module;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pda.ym.entity.response.NoDataResponse;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.CheckTaskAreaCodeAdapter;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.base.BaseTitleActivity;
import com.yimi.yinhepda.callbacks.EndlessRecyclerOnScrollListener;
import com.yimi.yinhepda.callbacks.OnClickCallBack;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.entity.bean.CheckTaskAreaCodeEntity;
import com.yimi.yinhepda.entity.bean.CurrentSpaceEntity;
import com.yimi.yinhepda.entity.bean.DispatchBigAreaEntity;
import com.yimi.yinhepda.entity.bean.DispatchSmallAreaEntity;
import com.yimi.yinhepda.entity.request.CheckTaskCreateRequest;
import com.yimi.yinhepda.entity.response.QueryDispatchBigAreaResponse;
import com.yimi.yinhepda.entity.response.QueryDispatchSmallAreaResponse;
import com.yimi.yinhepda.entity.response.QueryStorageResponse;
import com.yimi.yinhepda.entity.response.StorageInfo;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.net.QueryPlaceNetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.uce.commom.util.MyDialog;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 创建盘点单界面
 *
 * @author lj
 */
public class CheckTaskCreateActivity extends BaseTitleActivity {

    /**
     * 盘点人
     */
    private TextView tvCheckUser;
    private String deptCode;
    /**
     * 大区小区布局
     */
    private LinearLayout llBigSmallAreaCode;
    /**
     * 库区分类list
     */
    private List<CheckTaskAreaCodeEntity> storageClasses;
    /**
     * 库区类型list
     */
    private List<CheckTaskAreaCodeEntity> storageTypes;
    /**
     * 库区分类实体
     */
    private CheckTaskAreaCodeEntity storageClassEntity;
    /**
     * 库区类型实体
     */
    private CheckTaskAreaCodeEntity storageTypeEntity;
    /**
     * 库区实体
     */
    private CheckTaskAreaCodeEntity storageEntiyt;
    /**
     * 大区实体
     */
    private CheckTaskAreaCodeEntity dispatchbigEntity;
    /**
     * 小区实体
     */
    private CheckTaskAreaCodeEntity dispatchSmallEntity;
    /**
     * 场地实体
     */
    private CurrentSpaceEntity placeEntity;
    private TextView tvStorageClass;
    private TextView tvStorageType;
    private TextView tvStorage;
    private TextView tvDispatchBig;
    private TextView tvDispatchSmall;
    private TextView tvPlace;
    private LinearLayout llSmallArea;
    private LinearLayout llStorage;
    /**
     * 盘点场地布局
     */
    private LinearLayout llPlace;
    /**
     * 当前页数
     */
    private int currentPage;
    /**
     * 总页数
     */
    private int totalPage;
    /**
     * 一页数量
     */
    private final int pageSize = 50;
    /**
     * 库区场地
     */
    private boolean isPlaceEnable = false;

    @Override
    public String getPageName() {
        return "创建盘点任务";
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_check_task_create;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();
        initData();
    }

    private void initView() {
        tvCheckUser = findViewById(R.id.tv_checkUser);
        findViewById(R.id.ib_back).setOnClickListener(this);
        findViewById(R.id.ll_storage_class).setOnClickListener(this);
        findViewById(R.id.ll_storage_type).setOnClickListener(this);
        findViewById(R.id.ll_StorageArea).setOnClickListener(this);
        llBigSmallAreaCode = findViewById(R.id.ll_big_small_areaCode);
        llStorage = findViewById(R.id.ll_Storage);
        llPlace = findViewById(R.id.ll_place);
        tvStorageClass = findViewById(R.id.tv_storage_class);
        tvStorageType = findViewById(R.id.tv_storage_type);
        tvStorage = findViewById(R.id.tv_storage);
        tvDispatchBig = findViewById(R.id.tv_dispatch_big_areaCode);
        tvDispatchSmall = findViewById(R.id.tv_dispatch_samll_areaCode);
        tvPlace = findViewById(R.id.tv_place);
        findViewById(R.id.ll_bigArea).setOnClickListener(this);
        llSmallArea = findViewById(R.id.ll_smallArea);
        llSmallArea.setOnClickListener(this);
        llPlace.setOnClickListener(this);
        findViewById(R.id.btn_create).setOnClickListener(this);
    }

    private void initData() {
        llSmallArea.setEnabled(false);
        llBigSmallAreaCode.setVisibility(View.GONE);
        tvCheckUser.setText(sharedPreferUtil.getEmpName());
        deptCode = sharedPreferUtil.getDeptCode();
        //库区分类
        storageClasses = new ArrayList<>();
        storageClasses.add(new CheckTaskAreaCodeEntity("全部", "0"));
        storageClasses.add(new CheckTaskAreaCodeEntity("出发库区", "1"));
        storageClasses.add(new CheckTaskAreaCodeEntity("中转库区", "2"));
        storageClasses.add(new CheckTaskAreaCodeEntity("到达库区", "3"));
        //库区分类默认我中转库区
        storageClassEntity = new CheckTaskAreaCodeEntity("中转库区", "2");
        tvStorageClass.setText(storageClassEntity.getValueName());
        //库区类型
        storageTypes = new ArrayList<>();
        storageTypes.add(new CheckTaskAreaCodeEntity("全部", "0"));
        storageTypes.add(new CheckTaskAreaCodeEntity("正常库区", "1"));
        storageTypes.add(new CheckTaskAreaCodeEntity("异常库区", "2"));
        //库区类型默认为正常库区
        storageTypeEntity = new CheckTaskAreaCodeEntity("正常库区", "1");
        tvStorageType.setText(storageTypeEntity.getValueName());


        new QueryPlaceNetRequest()
                .setDeptCode(deptCode)
                .queryDataDict(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        isPlaceEnable = false;
                        llPlace.setVisibility(View.GONE);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        isPlaceEnable = true;
                        llPlace.setVisibility(View.VISIBLE);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_back:
                finish();
                break;
            case R.id.ll_storage_class:
                //库区分类
                showSelectDialog(1, "库区分类", storageClasses);
                break;
            case R.id.ll_storage_type:
                //库区类型
                showSelectDialog(2, "库区类型", storageTypes);
                break;
            case R.id.ll_StorageArea:
                //库区
                currentPage = 1;
                queryStorageRequest(null);
                break;
            case R.id.ll_bigArea:
                //查询派送大区数据
                currentPage = 1;
                queryDispatchBigArea(null);
                break;
            case R.id.ll_smallArea:
                //查询派送小区数据
                currentPage = 1;
                queryDispatchSmallArea(null);
                break;
            case R.id.ll_place:
                new QueryPlaceNetRequest()
                        .setDeptCode(deptCode)
                        .querySpaceByDept(new UICallBack() {
                            @Override
                            public void onError(String msg) {

                            }

                            @Override
                            public void onSuccess(Object obj) {
                                List<CurrentSpaceEntity> response = (List<CurrentSpaceEntity>) obj;

                                new QueryPlaceNetRequest()
                                        .showSelectSpaceDialog(CheckTaskCreateActivity.this, response, new OnClickCallBack() {
                                            @Override
                                            public void onCancle() {

                                            }

                                            @Override
                                            public void onSure(Object obj, Object obj1) {
                                                placeEntity = (CurrentSpaceEntity) obj;
                                                if (placeEntity != null) {
                                                    tvPlace.setText(placeEntity.getPlaceName());
                                                    tvPlace.setTag(placeEntity.getPlaceId());
                                                }
                                                Dialog dialog = (Dialog) obj1;
                                                dialog.cancel();
                                            }
                                        });
                            }
                        });
                break;
            case R.id.btn_create:
                //创建
                createSubmit();
                break;
            default:
                break;
        }
    }

    /**
     * 显示选择类型对话框
     *
     * @param type     类型：1-库区分类，2-库区类型，3-库区，4-大区，5-小区
     * @param title    类型名称
     * @param dataList 数据源
     */
    private void showSelectDialog(final int type, String title, final List<CheckTaskAreaCodeEntity> dataList) {
        final LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.alert_dialog_check_task_create, null);
        TextView tvTitle = layout.findViewById(R.id.tv_title);
        tvTitle.setText(title);
        RecyclerView rvListView = layout.findViewById(R.id.rv_listView);
        final Dialog dialog = new Dialog(this, R.style.AsyncTaskDialog);
        dialog.addContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.getWindow().getDecorView().setPadding(10, 10, 10, 10);
        WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(layoutParams);
        try {
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        final CheckTaskAreaCodeAdapter adapter = new CheckTaskAreaCodeAdapter(dataList, new CommonViewHolder.onItemCommonClickListener() {
            @Override
            public void onItemClickListener(int position) {
                dialog.dismiss();
                switch (type) {
                    case 1:
                        //库区分类
                        storageClassEntity = dataList.get(position);
                        tvStorageClass.setText(storageClassEntity.getValueName());
                        if (storageClassEntity.getValue().equals("3")) {
                            //选择达到库区，显示大区小区
                            llBigSmallAreaCode.setVisibility(View.VISIBLE);
                            llStorage.setVisibility(View.GONE);
                            storageEntiyt = null;
                            tvStorage.setText("——");
                        } else {
                            llBigSmallAreaCode.setVisibility(View.GONE);
                            llStorage.setVisibility(View.VISIBLE);
                            //非到达库区，大区小区设为空
                            dispatchbigEntity = null;
                            tvDispatchBig.setText("——");
                            dispatchSmallEntity = null;
                            tvDispatchSmall.setText("——");
                        }
                        if (storageClassEntity.getValue().equals("0")) {
                            storageClassEntity = null;
                        }
                        break;
                    case 2:
                        //库区类型
                        storageTypeEntity = dataList.get(position);
                        tvStorageType.setText(storageTypeEntity.getValueName());
                        if (storageTypeEntity.getValue().equals("0")) {
                            storageTypeEntity = null;
                        }
                        break;
                    case 3:
                        //库区
                        storageEntiyt = dataList.get(position);
                        tvStorage.setText(storageEntiyt.getValueName());
                        if (storageEntiyt.getValue().equals("0")) {
                            storageEntiyt = null;
                        }
                        break;
                    case 4:
                        //大区
                        dispatchbigEntity = dataList.get(position);
                        tvDispatchBig.setText(dispatchbigEntity.getValueName());
                        if (dispatchbigEntity.getValue().equals("0")) {
                            llSmallArea.setEnabled(false);
                            dispatchbigEntity = null;
                            dispatchSmallEntity = null;
                            tvDispatchSmall.setText(dataList.get(0).getValueName());
                        } else {
                            dispatchSmallEntity = null;
                            tvDispatchSmall.setText("——");
                            llSmallArea.setEnabled(true);
                        }
                        break;
                    case 5:
                        //小区
                        dispatchSmallEntity = dataList.get(position);
                        tvDispatchSmall.setText(dispatchSmallEntity.getValueName());
                        if (dispatchSmallEntity.getValue().equals("0")) {
                            dispatchSmallEntity = null;
                        }
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onItemLongClickListener(int position) {

            }
        });
        rvListView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        //分割线
        rvListView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        rvListView.setAdapter(adapter);
        //设置加载更多监听
        rvListView.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                adapter.setLoadState(adapter.LOADING);
                if (currentPage < totalPage) {
                    //请求下一页数据
                    currentPage++;
                    switch (type) {
                        case 3:
                            //库区
                            queryStorageRequest(new UICallBack() {
                                @Override
                                public void onError(String msg) {
                                    adapter.setLoadState(adapter.LOADING_ERROR);
                                }

                                @Override
                                public void onSuccess(Object obj) {
                                    List<CheckTaskAreaCodeEntity> entities = (List<CheckTaskAreaCodeEntity>) obj;
                                    dataList.addAll(entities);
                                    adapter.setLoadState(adapter.LOADING_COMPLETE);
                                }
                            });
                            break;
                        case 4:
                            //大区
                            queryDispatchBigArea(new UICallBack() {
                                @Override
                                public void onError(String msg) {
                                    adapter.setLoadState(adapter.LOADING_ERROR);
                                }

                                @Override
                                public void onSuccess(Object obj) {
                                    List<CheckTaskAreaCodeEntity> entities = (List<CheckTaskAreaCodeEntity>) obj;
                                    dataList.addAll(entities);
                                    adapter.setLoadState(adapter.LOADING_COMPLETE);
                                }
                            });
                            break;
                        case 5:
                            //小区
                            queryDispatchBigArea(new UICallBack() {
                                @Override
                                public void onError(String msg) {
                                    adapter.setLoadState(adapter.LOADING_ERROR);
                                }

                                @Override
                                public void onSuccess(Object obj) {
                                    List<CheckTaskAreaCodeEntity> entities = (List<CheckTaskAreaCodeEntity>) obj;
                                    dataList.addAll(entities);
                                    adapter.setLoadState(adapter.LOADING_COMPLETE);
                                }
                            });
                            break;
                        default:
                            break;
                    }
                } else {
                    // 显示加载到底的提示
                    adapter.setLoadState(adapter.LOADING_END);
                }
            }
        });
    }

    /**
     * 库区查询请求
     */
    private void queryStorageRequest(final UICallBack uiCallBack) {
        if (uiCallBack == null) {
            showPgDlg("数据查询中...");
        }
        Map<String, String> params = new HashMap<>(1);
        params.put("deptCode", deptCode);
        params.put("currentPage", currentPage + "");
        params.put("pageSize", pageSize + "");
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryStorageResponse.class)
                .setUrl(Constants.URL_QUERY_STORAGE)
                .setParams(params)
                .isDataBaseDownload(true)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        if (uiCallBack != null) {
                            uiCallBack.onError(msg);
                        }
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryStorageResponse response = (QueryStorageResponse) obj;
                        if (response != null) {
                            QueryStorageResponse.Data data = response.getData();
                            if (data != null) {
                                totalPage = data.getTotalPage();
                                List<StorageInfo> storageInfos = data.getRecords();
                                if (storageInfos != null && !storageInfos.isEmpty()) {
                                    List<CheckTaskAreaCodeEntity> entities = new ArrayList<>();
                                    for (StorageInfo info : storageInfos) {
                                        entities.add(new CheckTaskAreaCodeEntity(info.getStorage_name(), info.getStorage_code()));
                                    }
                                    if (uiCallBack == null) {
                                        entities.add(0, new CheckTaskAreaCodeEntity("——", "0"));
                                        showSelectDialog(3, "库区", entities);
                                    } else {
                                        uiCallBack.onSuccess(entities);
                                    }
                                } else {
                                    showToast("无库区！");
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 查询派送大区
     */
    private void queryDispatchBigArea(final UICallBack uiCallBack) {
        if (uiCallBack == null) {
            showPgDlg("数据查询中...");
        }
        Map<String, String> params = new HashMap<>(1);
        params.put("deptCode", deptCode);
        params.put("currentPage", currentPage + "");
        params.put("pageSize", pageSize + "");
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryDispatchBigAreaResponse.class)
                .setUrl(Constants.URL_DISPATCH_BIG_AREA)
                .setParams(params)
                .isDataBaseDownload(true)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        if (uiCallBack != null) {
                            uiCallBack.onError(msg);
                        }
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryDispatchBigAreaResponse response = (QueryDispatchBigAreaResponse) obj;
                        if (response != null) {
                            QueryDispatchBigAreaResponse.Data data = response.getData();
                            if (data != null) {
                                List<DispatchBigAreaEntity> dispatchBigAreaEntities = data.getRecords();
                                if (dispatchBigAreaEntities != null && !dispatchBigAreaEntities.isEmpty()) {
                                    List<CheckTaskAreaCodeEntity> entities = new ArrayList<>();
                                    for (DispatchBigAreaEntity entity : dispatchBigAreaEntities) {
                                        entities.add(new CheckTaskAreaCodeEntity(entity.getDispatchBigAreaName(), entity.getDispatchBigAreaCode()));
                                    }
                                    if (uiCallBack == null) {
                                        entities.add(0, new CheckTaskAreaCodeEntity("——", "0"));
                                        showSelectDialog(4, "派送大区", entities);
                                    } else {
                                        uiCallBack.onSuccess(entities);
                                    }
                                } else {
                                    showToast("无派送大区！");
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 查询派送小区
     */
    private void queryDispatchSmallArea(final UICallBack uiCallBack) {
        if (dispatchbigEntity == null) {
            showToast("大区未选择");
            return;
        }
        if (uiCallBack == null) {
            showPgDlg("数据查询中...");
        }
        Map<String, String> params = new HashMap<>(1);
        params.put("dispatchBigAreaCode", dispatchbigEntity.getValue());
        params.put("currentPage", currentPage + "");
        params.put("pageSize", pageSize + "");
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryDispatchSmallAreaResponse.class)
                .setUrl(Constants.URL_DISPATCH_SMALL_AREA)
                .setParams(params)
                .isDataBaseDownload(true)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryDispatchSmallAreaResponse response = (QueryDispatchSmallAreaResponse) obj;
                        if (response != null) {
                            QueryDispatchSmallAreaResponse.Data data = response.getData();
                            if (data != null) {
                                List<DispatchSmallAreaEntity> smallAreaEntities = data.getRecords();
                                if (smallAreaEntities != null && !smallAreaEntities.isEmpty()) {
                                    List<CheckTaskAreaCodeEntity> entities = new ArrayList<>();
                                    for (DispatchSmallAreaEntity entity : smallAreaEntities) {
                                        entities.add(new CheckTaskAreaCodeEntity(entity.getDispatchAreaName(), entity.getDispatchAreaCode()));
                                    }
                                    if (uiCallBack == null) {
                                        entities.add(0, new CheckTaskAreaCodeEntity("——", "0"));
                                        showSelectDialog(5, "派送小区", entities);
                                    } else {
                                        uiCallBack.onSuccess(entities);
                                    }
                                } else {
                                    showToast("无派送小区！");
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 请求创建盘点单
     */
    private void createSubmit() {

        /**
         * 盘库场地必填
         */
        if (isPlaceEnable) {
            if (placeEntity == null) {
                showToast("请选择一个盘库场地");
                return;
            }
        }


        CheckTaskCreateRequest request = new CheckTaskCreateRequest();
        //库区分类
        if (storageClassEntity != null) {
            request.setColumn2(storageClassEntity.getValue());
        } else {
            request.setColumn2("");
        }
        //库区分类为全部或是中转库区，则库区必须不为空
        if (storageClassEntity == null || storageClassEntity.getValue().equals("2")) {
            if (storageEntiyt == null || storageEntiyt.getValue().equals("0")) {
                showToast("请选择一个库区");
                return;
            }
        }

        //库区类型
        if (storageTypeEntity != null) {
            request.setColumn1(storageTypeEntity.getValue());
        } else {
            request.setColumn1("");
        }
        //派送大区
        if (dispatchbigEntity != null) {
            request.setColumn3(dispatchbigEntity.getValue());
        } else {
            request.setColumn3("");
        }
        //派送小区
        if (dispatchSmallEntity != null) {
            request.setColumn4(dispatchSmallEntity.getValue());
        } else {
            request.setColumn4("");
        }
        //库区
        if (storageEntiyt != null) {
            request.setStockArea(storageEntiyt.getValue());
        } else {
            request.setStockArea("");
        }
        if (placeEntity != null) {
            request.setColumn5(placeEntity.getPlaceCode());
        } else {
            request.setColumn5("");
        }


        //盘点人
        request.setStockUser(sharedPreferUtil.getValue(Common.USER_CODE));

        showPgDlg("数据提交中...");
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(NoDataResponse.class)
                .setUrl(Constants.URL_CHECK_TASK_CREATE)
                .setRequestObject(request)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        NoDataResponse response = (NoDataResponse) obj;
                        String data = response.getData();
                        if (data != null) {
                            if (data.equals("创建成功")) {
                                toActivity(CheckTaskActivity.class);
                                finish();
                            } else {
                                MyDialog.showAlertDialog(CheckTaskCreateActivity.this, data);
                            }
                        }
                    }
                });
    }

    @Override
    public boolean showBack() {
        return true;
    }

    @Override
    public void setBack() {
        finish();
    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

}
